<template>
  <div class="icon-config">
    <p class="title mb24 mt9">首页LOGO配置</p>
    <el-form :model="form" ref="formRef" label-width="170" style="max-width: 100%">
      <el-form-item
        label="设计师商城首页LOGO"
        :prop="`logoUrl`"
        :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
      >
        <div>
          <el-input v-show="false" v-model="form.logoUrl" placeholder="请输入网页导航名称“网页导航最顶部显示”"></el-input>
          <el-upload
            class="avatar-uploader"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="
              (file, fileList) => {
                handleAvatarChangeIcon('logoUrl', file, fileList);
              }
            "
          >
            <div class="upload-wrap">
              <template v-if="form.logoUrl">
                <img :src="form.logoUrl" class="td-img" />
                <div class="mask">
                  <el-icon class="ml6" style="color: white"> <RefreshRight /> </el-icon>重新上传
                </div>
                <div class="del-icon" @click.stop="delImg('logoUrl')">+</div>
              </template>
              <p v-else>
                <el-icon class="f22 mt4" style="font-weight: bold"><Plus /></el-icon>
              </p>
            </div>
          </el-upload>
          <i>建议尺寸：100*100px，请保持1:1规格，支持png/jpg格式</i>
        </div>
      </el-form-item>

      <div class="line"></div>

      <p class="title mb24">网页icon配置</p>
      <el-form-item
        label="网页导航栏名称"
        :prop="`webName`"
        :rules="{ required: true, message: '请输入', trigger: ['blur', 'change'] }"
      >
        <el-input v-model="form.webName" maxlength="20" placeholder="请输入网页导航名称“网页导航最顶部显示”"></el-input>
      </el-form-item>
      <el-form-item
        label="设计师商城网页icon"
        :prop="`iconUrl`"
        :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
      >
        <div>
          <el-input v-show="false" v-model="form.iconUrl" placeholder="请输入网页导航名称“网页导航最顶部显示”"></el-input>
          <el-upload
            class="avatar-uploader"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="
              (file, fileList) => {
                handleAvatarChangeIcon('iconUrl', file, fileList);
              }
            "
          >
            <div class="upload-wrap">
              <template v-if="form.iconUrl">
                <img :src="form.iconUrl" class="td-img" />
                <div class="mask">
                  <el-icon class="ml6" style="color: white"> <RefreshRight /> </el-icon>重新上传
                </div>
                <div class="del-icon" @click.stop="delImg('iconUrl')">+</div>
              </template>
              <p v-else>
                <el-icon class="f22 mt4" style="font-weight: bold"><Plus /></el-icon>
              </p>
            </div>
          </el-upload>
          <i>建议尺寸：100*100px，请保持1:1规格，支持png/jpg格式</i>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Plus, RefreshRight } from "@element-plus/icons-vue";
import { getLogoInfo, editLogo } from "@/apis/products/advert";
import { ElMessage } from "element-plus";

const form = ref({});
const formRef = ref();

onMounted(() => {
  getInfo();
});

const delImg = url => {
  form.value[url] = "";
  console.log(9090909);
};

const reset = () => {
  formRef.value.resetFields();
};

const getInfo = () => {
  getLogoInfo().then(res => {
    if (res.code === 200) {
      console.log("商城配置logo/icon信息===", res.data);
      form.value = res.data;
    }
  });
};

const getFormData = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      editLogo(form.value).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "修改成功",
            type: "success"
          });
          getInfo();
        }
      });
    }
  });
};

defineExpose({
  getFormData,
  reset
});

//====================================图片上传========================================================================================

import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
const handleAvatarChangeIcon = (key, file, fileList) => {
  //选中文件触发的change事件
  // console.log(file);
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
  if (!isPNG && !isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  } else {
    form.value[key] = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
    // console.log("这里调用图片上传接口");
    customUpload(key, { file }); //调用上传文件api接口
  }
};

/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (key, option) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl);
      form.value[key] = res.fileUrl.split("?")[0];
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
:deep(.el-upload.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}
.icon-config {
  padding: 0 20px;
  p.title {
    color: #131414;
    font-weight: bold;
    font-size: 18px;
  }
  i {
    font-style: normal;
    font-size: 12px;
    color: #86909c;
  }
  .line {
    height: 20px;
    background-color: #f5f7fa;
    margin: 40px -20px 40px -20px;
  }
  .upload-wrap {
    margin-top: 3px;
    position: relative;
    // height: 100%;
    .del-icon {
      position: absolute;
      color: white;
      width: 10px;
      height: 10px;
      border: 2px solid white;
      background-color: red;
      top: 4px;
      right: -4px;
      border-radius: 50%;
      line-height: 10px;
      transform: rotate(45deg);
    }
    .mask {
      display: none;
    }
    &:hover {
      .mask {
        position: absolute;
        top: 8px;
        left: 0;
        right: 0;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: white;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        transition: all 0.5s;
      }
    }

    img {
      width: 78px;
      height: 78px;
      border-radius: 6px;
      margin-top: 8px;
    }
  }
}
</style>
